package com.googlecode.cpbi.util;

import java.io.IOException;
import java.net.URL;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

/**
 * @author Jeremy Wales
 */
public class JarUtils {
	public static final JarInputStream NOT_A_JAR = null;

	private JarUtils() {
	}

	public static JarInputStream getJarInputStreamFrom(URL location) {
		try {
			return new JarInputStream(FileUtils.getInputStreamFrom(location));
		} catch (IOException e) {
			return NOT_A_JAR;
		}
	}

	public static boolean isJar(JarInputStream jarInputStream) {
		return jarInputStream != NOT_A_JAR;
	}

	public static boolean isJarUrl(URL url) {
		return ResourceUtils.URL_PROTOCOL_JAR.equals(url.getProtocol());
	}

	public static Manifest getManifestFrom(JarInputStream jarInputStream, String jarLocation) throws IOException {
		Manifest manifest = jarInputStream.getManifest();
		if (manifest == null) {
			manifest = getManifestFrom(jarLocation);
		}
		return manifest;
	}

	public static Manifest getManifestFrom(String jarLocation) throws IOException {
		JarFile jarFile = new JarFile(FileUtils.getFileAt(jarLocation));
		Manifest manifest = jarFile.getManifest();
		jarFile.close();
		return manifest;
	}

	public static Resource getJarEntryAt(URL jarLocation, String jarEntryName) {
		return FileUtils.getResourceAt(ResourceUtils.URL_PROTOCOL_JAR + ":" + jarLocation + ResourceUtils.JAR_URL_SEPARATOR + jarEntryName);
	}
}
